from celery import shared_task
from django.conf import settings
import os
import time
from django.core.files.storage import default_storage

@shared_task
def upload_expired_files():
    storage = default_storage
    media_root = settings.MEDIA_ROOT
    
    for root, dirs, files in os.walk(media_root):
        for filename in files:
            filepath = os.path.join(root, filename)
            rel_path = os.path.relpath(filepath, media_root)
            
            # 检查文件过期时间（24小时）
            create_time = os.path.getctime(filepath)
            if (time.time() - create_time) > settings.LOCAL_FILE_EXPIRE_HOURS * 3600:
                # 上传到OSS
                with open(filepath, 'rb') as f:
                    if not storage.exists_oss(rel_path):
                        storage.oss_storage.save(rel_path, f)
                
                # 删除本地文件
                os.remove(filepath)